package com.jingyanzi.privilege.service.impl;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.MessageDigest;
import java.util.List;
import java.util.Properties;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


import com.jingyanzi.privilege.dao.SecurityResourceMapper;
import com.jingyanzi.privilege.domain.ResourceDO;
import com.jingyanzi.privilege.domain.result.ResultDO;
import com.jingyanzi.privilege.domain.result.ResultSupport;
import com.jingyanzi.privilege.entity.SecurityResource;
import com.jingyanzi.privilege.entity.SecurityResourceExample;
import com.jingyanzi.privilege.factory.PrivilegeFactory;
import com.jingyanzi.privilege.init.InitData;
import com.jingyanzi.privilege.service.IResourceService;

@Service("resourceService")
public class ResourceServiceImpl implements IResourceService {
	
	private static Logger logger = Logger.getLogger(ResourceServiceImpl.class);

	@Autowired
	private SecurityResourceMapper resourceMapper;
	
	@Autowired
	private InitData initData;

	@Override
	public ResultDO checkUpdate() {
		String path = "";
		String temp_names = "";
		String[] names = null;
		Properties properties = new Properties();

		ResultSupport resultDO = new ResultSupport();

		InputStream in = PrivilegeFactory.class.getClassLoader().getResourceAsStream("application.properties");
		try {
			properties.load(in);
		} catch (IOException e) {
			e.printStackTrace();
		}

		if (properties.getProperty("resource_file_path") != null) {
			path = properties.getProperty("resource_file_path");
		} else {
			try {
				throw new Exception();
			} catch (Exception e) {
				e.printStackTrace();
				e.printStackTrace();
				resultDO.setSuccess(false);
				resultDO.setErrorMsg("系统错误");
				return resultDO;
			}
		}

		if (properties.getProperty("resource_file_names") != null) {
			temp_names = properties.getProperty("resource_file_names");
		} else {
			try {
				throw new Exception();
			} catch (Exception e) {
				e.printStackTrace();
				e.printStackTrace();
				resultDO.setSuccess(false);
				resultDO.setErrorMsg("系统错误");
				return resultDO;
			}
		}
		names = temp_names.split(",");

		for (String name : names) {
			logger.info(" ____________________________________________________");
			logger.info("|                SYSTEM INIT DATA                    |");
			logger.info("|            Now Read file :" + name + "             |");
			
			SecurityResourceExample example = new SecurityResourceExample();
			int count = 0;
			String md5Hex = getMd5Hex(path, name);
			
			example.createCriteria().andMd5EqualTo(md5Hex).andNameEqualTo(name);
			try {
				count = resourceMapper.countByExample(example);
			} catch (Exception e) {
				e.printStackTrace();
				resultDO.setSuccess(false);
				resultDO.setErrorMsg("系统错误");
				return resultDO;
			}
			ResourceDO res = new ResourceDO();
			res.setMd5(md5Hex);
			res.setName(name);
			res.setPath(path);
			if (count == 0) {
				logger.info("|                Write data to Database              |");
				init(res);
			} else {
				logger.info("|                Not New data                        |");
			}
			logger.info("|                     init End                       |");
			logger.info("|____________________________________________________|");
		}
		return resultDO;
	}

	private boolean init(ResourceDO res) {

		try {
			if (!initData.init(res)) {
				return false;
			}
		} catch (Exception e1) {
			e1.printStackTrace();
			return false;
		}

		SecurityResource entity = new SecurityResource();

		SecurityResourceExample example = new SecurityResourceExample();
		List<SecurityResource> list = null;
		example.createCriteria().andNameEqualTo(res.getName());
		try {
			list = resourceMapper.selectByExample(example);
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}

		if (list.size() == 0) {
			entity.setName(res.getName());
			entity.setMd5(res.getMd5());
			try {
				resourceMapper.insertSelective(entity);
			} catch (Exception e) {
				e.printStackTrace();
				return false;
			}
		} else {
			entity = list.get(0);
			if(!entity.getMd5().equals(res.getMd5())) {
				entity.setMd5(res.getMd5());
				System.out.println("update res md5");
				try {
					resourceMapper.updateByPrimaryKeySelective(entity);
				} catch (Exception e) {
					e.printStackTrace();
					return false;
				}
			}
		}
		return true;
	}

	

	private String getMd5Hex(String path, String name) {
		int len = 0;
		byte[] buffer = new byte[1024 * 8];
		FileInputStream in = null;
		String md5Hex = null;

		try {
			MessageDigest md5 = MessageDigest.getInstance("MD5");
			in = new FileInputStream(path + name);

			while ((len = in.read(buffer)) != -1) {
				md5.update(buffer, 0, len);
			}
			md5Hex = DigestUtils.md5Hex(md5.digest());
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				in.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			in = null;
			buffer = null;
		}
		return md5Hex;
	}
	
	
	public static void main(String[] rags) {
		int len = 0;
		byte[] buffer = new byte[1024 * 8];
		FileInputStream in = null;
		String md5Hex = null;

		try {
			MessageDigest md5 = MessageDigest.getInstance("MD5");
			in = new FileInputStream("d:/res/btn.json");

			while ((len = in.read(buffer)) != -1) {
				md5.update(buffer, 0, len);
			}
			md5Hex = DigestUtils.md5Hex(md5.digest());
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				in.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			in = null;
			buffer = null;
		}
		System.out.println(md5Hex);
	}

}
